from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

from rango.models import Page, Category
from rango.forms import CategoryForm
from django.contrib.auth.decorators import login_required

from rango.utils.general import run_query

def suggest_category(request):
    context = RequestContext(request)
    cat_list = []
    starts_with = ''
    if request.method == 'GET':
        starts_with = request.GET['suggestion']
    cat_list = get_category_list(8, starts_with)
    
    return render_to_response('rango/category_list.html', {'cat_list': cat_list }, context)

@login_required
def like_category(request):
    context = RequestContext(request)
    cat_id = None
    if request.method == 'GET':
        cat_id = request.GET['category_id']
    
    likes = 0
    if cat_id:
        category = Category.objects.get(id=int(cat_id))
        if category:
            likes = category.likes + 1
            category.likes =  likes
            category.save()

    return HttpResponse(likes)

def category(request, category_id):
    context = RequestContext(request)
    
    context_dict = {'cat_list':get_category_list(),}
    try:
        category = Category.objects.get(id=category_id)
        pages = None
        try:
            pages = Page.objects.filter(category=category).order_by('-views')
        except Page.DoesNotExist:
            pages = None
        
        context_dict['category'] = category
        context_dict['pages'] = pages
        
    except Category.DoesNotExist:
        print "Category with id = %r does not existed" % category_id
        pass
        
    if request.method == 'POST':
        query = request.POST['query'].strip()
        if query:
            result_list = run_query(query)
            context_dict['result_list'] = result_list
    
    return render_to_response('rango/category.html', context_dict, context)

@login_required
def add_category(request):
    context = RequestContext(request)
    
    if request.method == "POST":
        form = CategoryForm(request.POST)
        
        if form.is_valid():
            form.save(commit=True)
            
            return index(request)
        else:
            print form.errors
            
    else:
        form = CategoryForm()
    return render_to_response('rango/add_category.html', {'form':form, 'cat_list': get_category_list()}, context)
    
def get_category_list(max_result=0, starts_with=''):
    cat_list = []
    if starts_with:
        cat_list = Category.objects.filter(name__istartswith=starts_with)
    else:
        cat_list = Category.objects.all()
    if max_result>0:
        if len(cat_list) > max_result:
            cat_list=cat_list[:max_result]
    
    for cat in cat_list:
        cat.url = cat.id
        
    return cat_list